<template>
    <div class="chapters">
        <div class="nav" v-if="isshow">
            哔哩哔哩漫画
            <span class="iconfont icon-fanhui" @click="back()"></span>
        </div>
        <ul v-if="moreImageToken.length > 0" @click.stop="isshow = !isshow">
            <li v-for="(item, index) in moreImageToken" :key="index">
                <van-image
                    width="100vw"
                    fit="cover"
                    lazy-load
                    style="display: block"
                    :src="`${item.url}?token=${item.token}`"
                />
            </li>
            <div class="more" @click.stop="more">下一话</div>
        </ul>

        <van-loading
            v-else
            size="24px"
            vertical
            text-color="#0094ff"
            color="#0094ff"
            class="loading"
            >加载中...</van-loading
        >
    </div>
</template>
<script>
import _ from "lodash";
import { mapMutations } from "vuex";
export default {
    props: {
        idlist: {
            type: Array,
            define: () => {
                return [];
            },
        },
        id: {
            type: String,
            define: "",
        },
        locked: {
            type: Boolean,
            define: true,
        },
        comicid: {
            type: String,
            define: "",
        },
    },
    data() {
        return {
            chapters: [], //漫画章节内容
            chaptersImages: [], //漫画图片
            chunckedImages: [], //漫画图片 分割成二维数组
            ImageToken: [], //token
            isshow: false,
            page: 1,
            pageNum: 5,
            moreImageToken: [],
        };
    },
    created() {
        this.getchapters();
        this.readLog();
        if (this.locked) {
            this.$dialog
                .alert({
                    message: "该章节需要收费",
                })
                .then(() => {
                    this.$router.back();
                });
        }
    },
    mounted() {
        window.addEventListener("scroll", this.windowScroll);
    },
    beforeDestroy() {
        window.removeEventListener("scroll", this.windowScroll);
    },
    methods: {
        async getchapters(id = this.id) {
            await this.axios.get(`GetImageIndex?epId=${id}`).then((res) => {
                this.chapters = res;
                this.chunckedImages = _.chunk(res.images, 10);
                this.getImageToken();
            });
        },
        getImageToken() {
            this.ImageToken = [];
            if (!this.chapters.images) return;

            Promise.all(
                this.chunckedImages.map((secondArr) =>
                    this.axios.get(
                        "ImageToken?urls=" +
                            JSON.stringify(secondArr.map((o) => o.path + "@660w.jpg")) +
                            "&t=" +
                            Number.parseInt(Date.now() / (1000 * 60))
                    )
                )
            ).then((res) => {
                this.ImageToken = res.flatMap((v) => v);
                this.moreImageToken = this.ImageToken.splice(
                    (this.page - 1) * this.pageNum,
                    this.page * this.pageNum
                );
            });
        },
        back() {
            this.$router.back();
        },
        loadMore() {
            this.page++;
            this.moreImageToken = this.moreImageToken.concat(
                this.ImageToken.splice(this.page - 1, this.pageNum)
            );
        },
        windowScroll: _.throttle(function () {
            let scrollTop = document.body.scrollTop || document.documentElement.scrollTop;

            scrollTop = Math.ceil(scrollTop);
            //页面的高度
            let contentHight = document.body.scrollHeight;
            //窗口内容的高度
            let clientHeight = window.innerHeight;
            if (scrollTop + clientHeight >= contentHight) {
                this.loadMore();
            }
        }, 300),

        more: _.throttle(function () {
            let nextid;
            let id = this.idlist.find((item, index) => {
                if (index + 1 >= this.idlist.length) {
                    index = 0;
                } else {
                    if (this.id == this.idlist[index]) {
                        nextid = this.idlist[index + 1];
                    }
                }
                return nextid == this.idlist[index];
            });

            if (this.id == this.idlist[this.idlist.length - 1]) {
                this.getchapters(this.idlist[0]);
            } else {
                this.getchapters(id);
            }
        }, 300),

        ...mapMutations(["addReadLog"]),

        readLog() {
            let readHistory = localStorage.getItem("readLog");
            if (readHistory) {
                readHistory = JSON.parse(readHistory);
            }
            if (readHistory) {
                let arr = readHistory.filter((v) => v.comicid == this.comicid);
                arr.forEach((v) => {
                    v.ep_list.push(this.id);
                    let readLog = {
                        comicid: this.comicid,
                        ep_list: [],
                        time: new Date().getTime(),
                    };
                    readLog.ep_list = v.ep_list;
                    this.$store.commit("addReadLog", readLog);
                });
                if (arr.length == 0) {
                    let readLog = {
                        comicid: this.comicid,
                        ep_list: [],
                        time: new Date().getTime(),
                    };
                    readLog.ep_list.push(this.id);
                    this.$store.commit("addReadLog", readLog);
                }
            } else {
                let readLog = {
                    comicid: this.comicid,
                    ep_list: [],
                    time: new Date().getTime(),
                };
                readLog.ep_list.push(this.id);
                this.$store.commit("addReadLog", readLog);
            }
        },
    },
};
</script>

<style lang="scss" scoped>
.chapters {
    position: relative;

    .nav {
        position: fixed;
        background: #fff;
        text-align: center;
        font-size: 16px;
        line-height: 45px;
        width: 100%;
        z-index: 100;
        span {
            position: absolute;
            left: 12px;
            top: 0;
            bottom: 0;
        }
    }
    ul {
        li {
            img {
                width: 100%;
            }
        }
    }
    .loading {
        padding-top: 30px;
    }
    .more {
        text-align: center;
        line-height: 40px;
    }
}
</style>
